/*
 * @Description: 请求参数函数
 * @Author: zhangwei
 * @Date: 2023-03-15 20:31:33
 * @LastEditTime: 2023-03-18 22:30:02
 * @LastEditors: zw 775925302@qq.com
 */

import type {RequestAction} from "../types/lowcode"

/**
 *    根据传入的参数获得完整的请求对象
 * @param action 
 * @param routeValue 
 * @returns 
 */
export function useParseParam(action:RequestAction, routeValue:Recordable|undefined){
    var {url, method, params} = {...action}
    var _request = {
        url:url,
        method:method,
        params:{},
    }
    
    if(params?.default){
        params.default.forEach(v=>{
            _request.params[v.key] = v.value
        })
    }

    if(params?.router && routeValue){
        params.router.forEach(v=>{
            _request.params[v.key] = routeValue[v.routerKey]
        })
    }

    return _request
}

/**
 *   获取表单更新参数要解决几个问题：
 * 1. 默认的data是包含了从详情返回的所有值
 * 2. 更新时，只取配置了的值
 * 3. 要忽略掉属性为disabled的值
 */
export function useGetFormUpdateParam(reqBody, formSchema, keyField:string){
    reqBody.params[keyField] = formSchema?.data[keyField]
    //过滤掉disabled的
    formSchema?.widgets.forEach(v=>{
        if(!v.disabled){
            reqBody.params[v.key] = formSchema?.data[v.key]
        }
    })
}

export function useRemoveEmptyObject(data:Recordable){
    var newData = {...data};
    for(var key in newData){
        let source  = newData[key]
        if(source == null || source === undefined){
            delete newData[key]
        }else if(source instanceof Array && source.length == 0){
            delete newData[key]
        }else if (typeof source == "string" && source.trim().length == 0) {
            delete newData[key]
        }     
    }
    return newData
}